<template>
  <div
    ref="chartContainer"
    :id="echartsId"
    :class="className"
    :style="{ height, width }"
  />
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from "vue";
import * as echarts from "echarts";

const props = defineProps({
  className: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "100%",
  },
  loading: {
    type: Boolean,
    default: true,
  },
  fullOptions: {
    type: Object,
    default: () => ({}),
    required: true,
  },
});
const emits = defineEmits(["pageChange", "handleSelectionChange"]);
const echartsId = ref("echarts-" + Math.random().toString(36).substr(2, 9));
const chartContainer = ref(null);
let myChart;
let resizeObserver;
const initChart = () => {
  myChart = echarts.init(chartContainer.value, { renderer: "Canvas" });
  myChart.showLoading({
    text: "",
    color: "#0C96D2",
    textColor: "#000",
    maskColor: "rgba(0, 0, 0, .05)",
    zlevel: 0,
    lineWidth: 2,
  });
  if (!props.loading) {
    myChart.hideLoading();
    myChart.setOption(props.fullOptions.options, true);
  }
  myChart.on("click", () => emits("queryDetail"));
};
const handleResize = () => {
  if (myChart) myChart.resize();
};
onMounted(async () => {
  await nextTick();
  initChart();
  resizeObserver = new ResizeObserver(handleResize);
  if (chartContainer.value) {
    resizeObserver.observe(chartContainer.value);
  }
});
onBeforeUnmount(() => {
  if (resizeObserver) {
    resizeObserver.unobserve(chartContainer.value);
    resizeObserver.disconnect();
  }
  if (myChart) {
    myChart.dispose();
  }
});
watch(
  () => [props.fullOptions.options, props.loading],
  () => {
    if (!props.loading && myChart) {
      myChart.hideLoading();
      myChart.setOption(props.fullOptions.options, true);
    }
  },
  { deep: true }
);
</script>
